package com.java2e.martin.erd.service.sql;

import cn.fisok.pdman.dbreverse.Entity;
import cn.fisok.pdman.dbreverse.Module;
import cn.fisok.pdman.dbreverse.ParseDataModel;
import com.alibaba.druid.sql.ast.SQLStatement;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @author xiaobai
 */
@Service
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
public class StatementProcessor {

    /**
     * 收集系统中所有的 {@link StatementParser} 接口的实现。
     */
    private final Map<String, StatementParser> statementParserMap;

    /**
     * processStatement
     *
     * @param stmtList stmtList
     * @param dbType dbType
     * @return ParseDataModel
     */
    public ParseDataModel processStatement(List<SQLStatement> stmtList, String dbType) {
        if ("sqlserver".equalsIgnoreCase(dbType) || "postgresql".equalsIgnoreCase(dbType)) {
            dbType = "basic";
        }

        StatementParser statementParser = statementParserMap.get(dbType.toLowerCase() + StatementParser.class.getSimpleName());
        if (statementParser == null) {
            return null;
        }

        ParseDataModel parseDataModel = new ParseDataModel();
        Module module = new Module();
        parseDataModel.setDbType(dbType);
        parseDataModel.setModule(module);

        List<Entity> entities = new ArrayList<>(20);
        statementParser.parseStatement(stmtList, entities);
        module.setEntities(entities);
        return parseDataModel;
    }


}
